package com.nathan.mq.integration.vender.redismq;

import com.nathan.mq.integration.constant.MQVenderCS;
import java.util.Map;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.MapUtils;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.SmartInitializingSingleton;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationListener;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.event.ContextClosedEvent;
import org.springframework.stereotype.Component;

/**
 * @Description:
 * @Author: zhujunjie
 * @Date: 2021/12/9 17:20
 */
@Slf4j
@Component
@ConditionalOnProperty(name = MQVenderCS.YML_VENDER_KEY, havingValue = MQVenderCS.REDIS_MQ)
public class RedissonBeanProcessor implements ApplicationListener<ContextClosedEvent>, ApplicationContextAware, SmartInitializingSingleton {

    private RedisQueueBean<Object> queueBean;
    private ConfigurableApplicationContext applicationContext;

    @Override
    public void setApplicationContext(@NotNull ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = (ConfigurableApplicationContext) applicationContext;

    }

    @Override
    public void onApplicationEvent(@NotNull ContextClosedEvent closedEvent) {
        queueBean.removeAllListener();
        queueBean.removeSubscribeListener();
    }

    @Override
    public void afterSingletonsInstantiated() {
        Map<String, RedisMqListener> map = applicationContext.getBeansOfType(RedisMqListener.class);
        if (MapUtils.isNotEmpty(map)) {
            queueBean = new RedisQueueBean<>(map, applicationContext);
            try {
                queueBean.initQueueBean();
            } catch (Exception e) {
                throw new IllegalStateException(e.getMessage(), e);
            }
        }
    }

}
